<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from 'echarts';
import { defineComponent, shallowRef } from 'vue';
import macaronsTheme from '@/styles/echarts/theme/macarons'; // echarts theme
import resize from './mixins/resize';
import { userNumber } from '@/api/homePage.js'
import eventBus from '@/utils/eventBus'



const animationDuration = 6000;

export default defineComponent({
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    }
  },
  data () {
    return {
      chart: null
    };
  },
  mounted () {
    eventBus.on('typeChange', (msg) => {
      console.log('圖表收到消息', msg)
      if (msg.chart == 'bar') {
        this.getUserNumber(msg.type)
      }
    })
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeUnmount () {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    getUserNumber (type = 1) {
      userNumber({ type: type }).then((res) => {
        console.log(res)
        this.setOptions(res.data.time, res.data.value)
      })
    },
    initChart () {
      this.chart = shallowRef(echarts.init(this.$el, macaronsTheme));
      this.getUserNumber()



    },
    setOptions (xdata, ydata) {
      this.chart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          top: 10,
          left: '2%',
          right: '2%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [{
          type: 'category',
          data: xdata,
          axisTick: {
            alignWithLabel: true
          }
        }],
        yAxis: [{
          type: 'value',
          axisTick: {
            show: false
          }
        }],
        series: [{
          name: 'pageA',
          type: 'bar',
          stack: 'vistors',
          barWidth: '60%',
          data: ydata,
          animationDuration
        }]
      });
    }
  }
});
</script>
